package com.sita.cfmoto.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.model.LatLng;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.kyleduo.switchbutton.SwitchButton;
import com.sita.cfmoto.R;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.support.LocationController;
import com.sita.cfmoto.ui.fragments.BasicMapFragment;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.LogUtils;
import com.sita.cfmoto.utils.VehicleUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;

public class GeofenceSettingActivity extends ActivityBase {
    private final int GEOFENCE_MIN_DISTANCE = 100;
    private final int GEOFENCE_MAX_DISTANCE = 20000;
    String TAG = GeofenceSettingActivity.class.getSimpleName();
    @Bind(R.id.geofence_btn_setting)
    Button mBtnSetting;
    @Bind(R.id.geofence_setting_value)
    EditText mEtSettingValue;
    @Bind(R.id.sb_default)
    SwitchButton mSbButton;
    BasicMapFragment mMapFragment;

    public static Intent newIntent() {
        return new Intent(GlobalContext.getGlobalContext(), GeofenceSettingActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_geofence_setting);
        ButterKnife.bind(this);
        mBtnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!LocalStorage.hasBindVehicle()) {
                    ToastUtils.show(getApplicationContext(), R.string.error_no_bind_vehicle);
                    return;
                }

                settingGeofence();
            }
        });

        initMapFragment();

        getDefaultSetting();

        mSbButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mEtSettingValue.setEnabled(isChecked);
                if (isChecked) {
                    LatLng latLng = mMapFragment.getCircleCenter();
                    mMapFragment.drawCircle(Integer.valueOf(mEtSettingValue.getText().toString())
                            , latLng.latitude
                            , latLng.longitude);
                }
            }
        });

        mEtSettingValue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!mSbButton.isChecked())
                    return;

                if (android.text.TextUtils.isEmpty(mEtSettingValue.getText().toString())) {
                    return;
                }
                try {
                    int value = Integer.valueOf(mEtSettingValue.getText().toString());
//                if (checkDistanceValue(value)) {
                    LatLng latLng = mMapFragment.getCircleCenter();
                    if (latLng != null) {
                        mMapFragment.drawCircle(value, latLng.latitude, latLng.longitude);
                    } else {
                        mMapFragment.drawCircle(value);
                    }
//                }
                } catch (Exception e) {

                }
            }
        });

        initToolbar(getResources().getString(R.string.geofence_setting));
    }

    private boolean checkDistanceValue(int value) {
        if (value > GEOFENCE_MAX_DISTANCE) {
            final NormalDialog dialog = new NormalDialog(GeofenceSettingActivity.this);
            dialog.content(getString(R.string.geofence_value_invalid_larger, GEOFENCE_MAX_DISTANCE))
                    .btnNum(1)
                    .btnText(getString(R.string.ok))//
                    .show();

            dialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    dialog.dismiss();
                }
            });
            return false;
        } else if (value < GEOFENCE_MIN_DISTANCE) {
            final NormalDialog dialog = new NormalDialog(GeofenceSettingActivity.this);
            dialog.content(getString(R.string.geofence_value_invalid_lower, GEOFENCE_MIN_DISTANCE))
                    .btnNum(1)
                    .btnText(getString(R.string.ok))//
                    .show();

            dialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    dialog.dismiss();
                }
            });
            return false;
        }
        return true;

    }


    private void initMapFragment() {
        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        if (mMapFragment == null) {
            mMapFragment = BasicMapFragment.newInstance(true, false);
        }
        ftx.replace(R.id.geofence_map_layout, mMapFragment, "");
        ftx.addToBackStack(null);
        ftx.commitAllowingStateLoss();

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void getDefaultSetting() {
        VehicleUtils.getGeofenceSetting(new VehicleUtils.FetchGeofenceSettingCallback() {
            @Override
            public void onResult(boolean result, boolean set, double lat, double lng, int range) {
                LogUtils.d(TAG, ":" + set + lat + lng + range);
                if (result) {
                    setUIData(lat, lng, range, set);
                } else {
                    AMapLocation loc = LocationController.getLastKnownLocation();
                    if (loc != null) {
                        setUIData(loc.getLatitude(), loc.getLongitude(), GEOFENCE_MIN_DISTANCE, false);
                    } else {
                        setUIData(VehicleUtils.vehicleBean.lat, VehicleUtils.vehicleBean.lng, GEOFENCE_MIN_DISTANCE, false);
                    }
                }
            }
        });
    }

    private void setUIData(double lat, double lng, int distance, boolean enabled) {
        mSbButton.setChecked(enabled);
        mEtSettingValue.setEnabled(enabled);
        if (enabled) {
            mEtSettingValue.setText(String.valueOf(distance));
            mMapFragment.drawCircle(distance, lat, lng);
        } else {
            mEtSettingValue.setText(String.valueOf(distance));
            mMapFragment.drawCircle(distance, lat, lng);
        }
    }

    private void settingGeofence() {
        if (mMapFragment != null && !android.text.TextUtils.isEmpty(mEtSettingValue.getText().toString())) {


            double lat = mMapFragment.getCircleCenter().latitude;
            double lng = mMapFragment.getCircleCenter().longitude;
            int distance = Integer.valueOf(mEtSettingValue.getText().toString());
            boolean set = mSbButton.isChecked();

            if (set && !checkDistanceValue(distance)) {
//                showSettingParamWrong();
                return;
            }

            VehicleUtils.setGeofence(new VehicleUtils.OnResultListener() {
                @Override
                public void onResult(boolean result) {
                    if (result) {
                        showSettingOk();
                    } else {
                        showSettingFail();
                    }
                }
            }, lat, lng, distance, set);
        }
    }

    private void showSettingOk() {
        final NormalDialog dialog = new NormalDialog(GeofenceSettingActivity.this);
        dialog.content("围栏设置成功")
                .btnNum(1)
                .btnText(getString(R.string.ok))//
                .show();

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        });
    }

    private void showSettingFail() {
        final NormalDialog dialog = new NormalDialog(GeofenceSettingActivity.this);
        dialog.content("围栏设置失败")
                .btnNum(1)
                .btnText(getString(R.string.ok))//
                .show();

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        });
    }

    private void showSettingParamWrong() {
        final NormalDialog dialog = new NormalDialog(GeofenceSettingActivity.this);
        dialog.content("围栏大小应该大于100米，小于50000米，请重新输入")
                .btnNum(1)
                .btnText(getString(R.string.ok))//
                .show();

        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        });
    }

    @OnClick(R.id.geofence_locate_me)
    void onClickLocateMe() {
        AMapLocation location = LocationController.getLastKnownLocation();
        if (location != null) {
            mMapFragment.setMapCenter(location.getLatitude(), location.getLongitude());
        }
    }

}
